<?php

/**
 * 数据操作
 *
 * php /path/aishang/index.php top auto
 *
 * @author 
 */
if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}
include_once APPPATH . "libraries/ExceptionHandler.php";
include_once APPPATH . "core/base_controller.php";
class taobao extends base_controller {

    var $taobaoclient = null;

    public function __construct() {
        parent::__construct();
        $this->load->model('authorizetokenmodel'); //授权表
        $this->load->model('pushsettingmodel');

        $this->load->model('ordermodel', 'apachorder');
        $this->load->model('detailmodel', 'apachdetail');
        $this->load->library('ApachSdk');
        $this->load->library('queue', array('key' => 'tbao_queue')); //队列
    }

    /*
     *  拉取订单消息
     *  add by tongxiaoyong     
     */

    public function obtainIncreOrder() {
        set_time_limit(0);
        $page = 1;
        $totalpages = 0;
        $startTime = date("Y-m-d H:i:s", strtotime('-1 day'));
        $endTime = date("Y-m-d H:i:s");
        //程序已在运行中即退出
        $running_log = APPPATH . "logs/obtainIncreOrder.run.lock";
        if (file_exists($running_log)) {
            return;
        }
        //创建运行锁
        file_put_contents($running_log, '1');
        $auths = $this->authorizetokenmodel->getEffectiveSellers(1);
        foreach ($auths as $auth) {
            try {
                $token = $auth['full_token'] ? unserialize($auth['full_token']) : null;
                if ($token) {
                    $this->api_client = new TaobaoClient(array($token));
                    $this->orderapi = new TradeAPI(array($this->api_client));
                    //记录读取时间
                    $log_last_run_file = APPPATH . "logs/" . $auth["user_id"] . ".taobaoruntime.log";
                    if (file_exists($log_last_run_file)) {
                        $text = file_get_contents($log_last_run_file);
                        $t = unserialize($text);
                        if (isset($t['endTime'])) {
                            $diff_time = time() - strtotime($t['endTime']);
                            if ($diff_time > 5184000) {
                                $t['endTime'] = date("Y-m-d", strtotime("-60 day")) . " 23:59:59";
                            }
                            $startTime = $t['endTime'];
                            $endTime = date('Y-m-d H:i:s');
                        }
                    }
                    //按时间分页读取数据
                    $output = '';
                    do {
                        $rs = $this->orderapi->getData($startTime, $endTime, $page);
                        if (isset($rs['data']['trades']) && $rs['data']['trades']) {
                            $odata = $rs['data']['trades'];
                            $ototal = $rs['total_records'];
                            foreach ($odata as $v) {
                                if ($v['tid']){
                                    $seristr = serialize(array('order_id' => $v['tid'], 'user_id' => $auth["user_id"]));
                                    $this->queue->push($seristr);
                                    $output.=$seristr . "\n";
                                }
                            }
                            $totalpages = ceil($ototal / 100); //默认pagesize是100
                            //记录拉取时间
                            if ($output) {
                                echo "当前页数" . $page . "\n";
                                echo "modify->start:" . $startTime . '---' . $endTime . "|" . $page . "\n";
                                echo $output;
                                file_put_contents($log_last_run_file, serialize(array('startTime' => $startTime, 'endTime' => $endTime)));
                                echo "modify->end \n";
                            }
                        }
                        $page++;
                    } while (($page - 1) < $totalpages);
                    $page = 1;
                    $totalpages = 0;
                    unset($this->api_client);
                    unset($this->orderapi);
                    unset($token);
                }
                sleep(5);
            } catch (Exception $e) {
                echo 'Caught exception: ', $e->getMessage(), "\n";
            }
        }
        unlink($running_log);
        echo "unlink log \n";
    }

    public function test() {
        set_time_limit(0);
        $page = 1;
        $totalpages = 0;
        $startTime = date("Y-m-d H:i:s", strtotime('-1 day'));
        $endTime = date("Y-m-d H:i:s");
        //程序已在运行中即退出
//        $running_log = APPPATH . "logs/obtainIncreOrdertest.run.lock";
//        if (file_exists($running_log)) {
//            return;
//        }
        //创建运行锁
//        file_put_contents($running_log, '1');
        $auths = $this->authorizetokenmodel->getSellersByChannel(1);
        if (isset($GLOBALS['argv'][3]) ) {
            $spec_user_id = $GLOBALS['argv'][3];
        }
        foreach ($auths as $auth) {
            if(isset($spec_user_id)){
                if($auth['user_id'] != $spec_user_id)
                    continue;
            }
            echo $auth['user_id'];
            try {
                $token = $auth['full_token'] ? unserialize($auth['full_token']) : null;
                if ($token) {
                    $this->api_client = new TaobaoClient(array($token));
                    $this->orderapi = new TradeAPI(array($this->api_client));
                    //记录读取时间
                    $log_last_run_file = APPPATH . "logs/" . $auth["user_id"] . ".taobaoruntime.log";
                    if (file_exists($log_last_run_file)) {
                        $text = file_get_contents($log_last_run_file);
                        $t = unserialize($text);
                        if (isset($t['endTime'])) {
                            $diff_time = time() - strtotime($t['endTime']);
                            if ($diff_time > 5184000) {
                                $t['endTime'] = date("Y-m-d", strtotime("-60 day")) . " 23:59:59";
                            }
                            $startTime = $t['endTime'];
                            $endTime = date('Y-m-d H:i:s');
                        }
                    }
                    //按时间分页读取数据
                    $output = '';
                    do {
                        $rs = $this->orderapi->getData($startTime, $endTime, $page);
                        if (isset($rs['data']['trades']) && $rs['data']['trades']) {
                            $odata = $rs['data']['trades'];
                            $ototal = $rs['total_records'];
                            foreach ($odata as $v) {
                                if ($v['tid']){
                                    $seristr = serialize(array('order_id' => $v['tid'], 'user_id' => $auth["user_id"]));
                                    $this->queue->push($seristr);
                                    $output.=$seristr . "\n";
                                }
                            }
                            $totalpages = ceil($ototal / 100); //默认pagesize是100
                            //记录拉取时间
                            if ($output) {
                                echo "当前页数" . $page . "\n";
                                echo "modify->start:" . $startTime . '---' . $endTime . "|" . $page . "\n";
                                echo $output;
                                file_put_contents($log_last_run_file, serialize(array('startTime' => $startTime, 'endTime' => $endTime)));
                                echo "modify->end \n";
                            }
                        }
                        $page++;
                    } while (($page - 1) < $totalpages);
                    $page = 1;
                    $totalpages = 0;
                    unset($this->api_client);
                    unset($this->orderapi);
                    unset($token);
                }
                sleep(5);
            } catch (Exception $e) {
                echo 'Caught exception: ', $e->getMessage(), "\n";
            }
        }
//        unlink($running_log);
        echo "end .. \n";
    }
    /*
     *  消费队列订单消息
     *  add by tongxiaoyong     
     */

    public function consumption() {
        set_time_limit(0);
        #开启个推送队列
        $wait_pushed_queue = new Queue(array('key'=>'wait_push_queue'));
        while (true) {
            try {
                $str = $this->queue->pop();
                $nowtime = time();
                $queue = unserialize($str);
                if (!$queue || !isset($queue['order_id']) || !isset($queue['user_id'])) {
                    continue;
                }
                //监测数据库连接状态
                if(@mysqli_ping($this->db->conn_id) === False){
                    echo "heart gone away\n";
                    $this->db->reconnect();
                    $this->db->initialize();
                }

                $authinfo = $this->authorizetokenmodel->getToken($queue['user_id'], 1);
                if (!$authinfo) {
                    continue;
                }
                if (!isset($authinfo->full_token)) {
                    usleep($queue_delay_time);
                    continue;
                }
                if (is_string($authinfo->full_token)) {
                    $authinfo->full_token = unserialize($authinfo->full_token);
                }
                $this->api_client = new TaobaoClient(array($authinfo->full_token));
                $this->orderapi = new TradeAPI(array($this->api_client));
                $tradeFullInfo = $this->orderapi->getFullInfoById($queue['order_id']);
                //跳过WAIT_BUYER_PAY
                if ($tradeFullInfo['status'] == 'WAIT_BUYER_PAY') {
                    continue;
                }
                echo $str . "\n";
                //配送时间设置
                $pushSetting = $this->pushsettingmodel->getPushSetting($authinfo->huaji_user_id);
                if ($pushSetting) {
                    switch ($pushSetting->delivery_usually_time) {
                        case "1":
                            $tradeFullInfo['deadline'] = isset($tradeFullInfo['pay_time']) ? $tradeFullInfo['pay_time'] : "";
                            break;
                        case "2":
                            $tradeFullInfo['deadline'] = isset($tradeFullInfo['pay_time']) ? date('Y-m-d H:i:s', strtotime($tradeFullInfo['pay_time']) + 86400) : "";
                            break;
                        case "3":
                            $tradeFullInfo['deadline'] = $pushSetting->delivery_custom;
                            break;
                    }
                }
                if ($tradeFullInfo) {
                    $this->apachorder->newtbOrderInfo($queue['user_id'], $tradeFullInfo);
                    $this->apachdetail->MoreTbItemInfo($tradeFullInfo['tid'], $tradeFullInfo['orders']);
                    //大于0自动推送订单
                    if (isset($pushSetting->push_time) && $pushSetting->push_time > 0 && in_array($tradeFullInfo['status'],array('WAIT_SELLER_SEND_GOODS','WAIT_BUYER_CONFIRM_GOODS','TRADE_BUYER_SIGNED','SELLER_CONSIGNED_PART'))) {
                        $push_time = date('Y-m-d H:i:s', time() + $pushSetting->push_time * 60);
                        $wait_pushed_queue->push(serialize(array(
                            'order_id' => $queue['order_id'],
                            'user_id' => $queue['user_id'],
                            'huaji_user_id' => $authinfo->huaji_user_id,
                            'push_time' => $push_time
                        )));
                    }
                }
                //通知新订单
                $notice_queue = new Queue(array('key'=>'ordermessage'.$authinfo->huaji_user_id));
                $notice_queue->pop();
                $notice_queue->push('{"num":1}');
            } catch (Exception $e) {
                $this->queue->push($str);
            }
            usleep(100000);
        }
    }

}
